package com.leyou.user.controller;


import com.leyou.item.pojo.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * //校验用户名和手机号
     *
     * @param data
     * @param type
     * @return
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkData(@PathVariable(value = "data") String data,
                                             @PathVariable(value = "type") Integer type) {
        try {
            Boolean flag = this.userService.checkData(data, type);
            if (flag!=null) {
                return ResponseEntity.ok(flag);//200
            }else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(flag);//400
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();//500
        }
    }

    /**
     * 发送短信
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendMessage(@RequestParam("phone") String phone) {

           Boolean boo= this.userService.sendCode(phone);
           if (boo!=null||boo){
               return ResponseEntity.status(HttpStatus.CREATED).build();
           }
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 注册业务
     */

    @PostMapping("register")
    public ResponseEntity<Void> saveUser(@Valid User user, @RequestParam("code") String code) {

       Boolean boo= this.userService.saveUser(user, code);
       if (boo){
           ResponseEntity.status(HttpStatus.CREATED).build();
       }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();

    }

    /**
     * 登入业务。user
     */

    @PostMapping("query")
    public ResponseEntity<User> queryUser(@RequestParam("username") String username,
                                          @RequestParam("password") String password) {

        try {
            User user = this.userService.queryUser(username,password);
            if (user == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            }
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
